<template>
  <Page class="bg-[#f5f7fa] min-h-screen">
    <!-- 顶部绿色渐变背景 -->
    <view
      class="sticky top-0 left-0 right-0 z-[2]"
    >
    <PageHeader title="签到任务" :showBack="true" :onlyBack="true" />
      <view
        class="bg-gradient-to-r from-[#4CAF50] to-[#81C784]  text-white px-[32rpx] pt-[100rpx] pb-[20rpx] rounded-b-[32rpx] mb-[-40rpx] shadow-md"
      >
        <!-- 返回按钮 -->
        <SearchView @search="handleSearch" />
      </view>
    </view>

    <!-- 吸顶搜索栏 -->
    <!-- <view class="sticky top-0 z-30 px-[32rpx] pt-[32rpx] pb-[0] bg-transparent">
      <SearchView placeholder="搜索签到任务..." />
      <view
        class="flex overflow-x-auto gap-x-[18rpx] py-[18rpx] scrollbar-hide"
      >
        <view
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="
            activeFilter === 0
              ? 'bg-gradient-to-r from-[#4CAF50] to-[#81C784] text-white font-bold shadow border-[#4CAF50]'
              : 'bg-[#f5f7fa] text-[#4CAF50]/80'
          "
          @click="activeFilterType(0, 0)"
        >
          全部任务
        </view>
        <view
          v-for="(filter, index) in filters"
          :key="index"
          class="px-[32rpx] py-[12rpx] rounded-[24rpx] text-[26rpx] font-medium cursor-pointer transition-all duration-200 border border-transparent whitespace-nowrap"
          :class="
            activeFilter === index + 1
              ? 'bg-gradient-to-r from-[#4CAF50] to-[#81C784] text-white font-bold shadow border-[#4CAF50]'
              : 'bg-[#f5f7fa] text-[#4CAF50]/80'
          "
          @click="activeFilterType(index + 1, filter.id)"
        >
          {{ filter.name }}
        </view>
      </view>
    </view> -->

    <!-- 内容区 -->
    <view class="pt-[20rpx] pb-[32rpx] px-[0]">
      <view class="p-[24rpx_32rpx] flex flex-col gap-y-[24rpx]">
        <!-- 签到任务列表 -->
        <view
          v-for="(task, index) in checkinTasks"
          :key="index"
          class="bg-white rounded-[24rpx] p-[32rpx] shadow-sm border border-[#f0f0f0] relative flex flex-col transition-all duration-300 mb-[24rpx]"
        >
          <!-- 头部 -->
          <view class="flex justify-between items-center mb-[16rpx]">
            <view class="text-[36rpx] font-bold text-[#222] flex-1 truncate">{{ task.title }}</view>
          </view>

          <!-- 任务描述 -->
          <view
            class="text-[28rpx] text-[#666] mb-[16rpx] leading-[1.6] line-clamp-2"
          >{{ task.describe_str || '暂无任务描述' }}</view>

          <!-- 任务要求 -->
          <view class="bg-[#f8f9fa] rounded-[16rpx] p-[24rpx] border-l-[6rpx] border-l-[#4CAF50] mb-[16rpx]">
            <view class="text-[26rpx] font-medium mb-[6rpx] text-[#666]">任务地址：{{ task.full_address }}</view>
          </view>

          <!-- 元信息 -->
          <view
            class="flex justify-between text-[26rpx] text-[#666] mb-[16rpx]"
          >
            <view>
              <view class="mb-[4rpx]">签到日期：{{ task.start_date }} 至 {{ task.end_date }}</view>
              <view>签到时间段：{{ task.check_time }} 至 {{ task.deadline }}</view>
            </view>
            <view
              class="text-[32rpx] font-bold text-[#FF9800] text-right my-[8rpx]"
            >¥{{ task.task_amount }}</view>
          </view>

          <!-- 标签 -->
          <view class="flex flex-wrap gap-x-[12rpx] gap-y-[12rpx] mb-[16rpx]">
            <view
              v-for="(tag, tIndex) in task.tags"
              :key="tIndex"
              class="text-[24rpx] px-[16rpx] py-[6rpx] bg-[#e8f5e9] rounded-[10rpx] text-[#4CAF50] font-medium"
            >
              {{ tag }}
            </view>
          </view>

          <!-- 底部操作按钮 -->
          <view class="flex justify-end items-center mt-[12rpx] gap-[12rpx]">
            <nut-button
              size="small"
              type="success"
              class="text-[28rpx] rounded-[20rpx]"
              @click="handleViewDetail(task)"
            >
              查看详情
            </nut-button>

            <!-- 根据任务状态显示不同按钮 -->
            <template v-if="task.status === 'pending'">
              <nut-button size="small" type="warning" class="text-[28rpx] rounded-[20rpx]" disabled>
                审核中
              </nut-button>
            </template>

            <template v-else-if="task.status === 'approved'">
              <nut-button
                size="small"
                type="info"
                class="text-[28rpx] rounded-[20rpx]"
                @click="handleViewDetail(task)"
              >
                查看详情
              </nut-button>
            </template>

            <template v-else-if="task.status === 'rejected'">
              <nut-button
                size="small"
                type="default"
                class="text-[28rpx] rounded-[20rpx]"
                @click="handleReapply(task)"
              >
                重新申请
              </nut-button>
            </template>

            <template v-else>
              <nut-button
                size="small"
                type="primary"
                class="text-[28rpx] rounded-[20rpx] bg-[#2196F3] border-[#2196F3]"
                @click="handleApplyTask(task)"
              >
                申请任务
              </nut-button>
            </template>
          </view>
        </view>
      </view>
    </view>
    <!-- 加载更多按钮 -->
    <view class="flex justify-center mt-[20rpx] mb-[30rpx]">
      <nut-button
        size="normal"
        type="primary"
        :loading="isLoading"
        :disabled="isLoading || noMore"
        @click="loadMore"
        class="w-[300rpx] bg-[#2196F3] border-[#2196F3] rounded-[24rpx] py-[16rpx] text-[28rpx] font-medium shadow-sm transition-all duration-300"
      >
        {{ noMore ? "没有更多了" : "加载更多" }}
      </nut-button>
    </view>
  </Page>
</template>

<script setup lang="ts">
import { ref } from "vue";
import Taro from "@tarojs/taro";
import SearchView from "@/components/SearchView.vue";
import { post } from "@/utils/request";

// 定义任务状态类型
type TaskStatus = "pending" | "approved" | "rejected" | "unapplied";

// 分页参数
const pageNo = ref(1); // 当前页码
const pageSize = ref(5); // 每页条数
const isLoading = ref(false); // 加载中状态
const noMore = ref(false); // 是否没有更多数据



// 定义接口
interface CheckinTaskItem {
  id?: number;
  title?: string; // 任务标题
  status?: TaskStatus; // 任务状态：pending(审核中)、approved(已通过)、rejected(已拒绝)、unapplied(未申请)
  desc?: string; // 任务描述
  brief_introduction?: string; // 简要介绍
  requirement?: string; // 任务要求
  startTime?: string; // 开始时间
  endTime?: string; // 结束时间
  deadline?: string; // 截止时间
  points?: number; // 积分奖励
  task_amount?: number; // 任务金额
  full_address?: string; // 完整地址
  tags?: string[]; // 任务标签
  participantCount?: number; // 参与人数
  locationRequired?: boolean; // 是否需要定位签到
  checkinLocation?: {
    // 签到地点
    name?: string;
    latitude?: number;
    longitude?: number;
    radius?: number; // 允许签到的半径范围(米)
  };
}

// 筛选条件
const filters = ref<{ id: number; name: string }[]>([]);
const activeFilter = ref(0);
const searchValue = ref("");
const handleSearch = (value: string) => {
  searchValue.value = value;
  console.log("searchValue==>", searchValue.value);
  resetPagination(); // 重置分页
  getCheckinTasks();
};

// 重置分页参数
const resetPagination = () => {
  pageNo.value = 1;
  checkinTasks.value = [];
  noMore.value = false;
};

// 加载更多
const loadMore = () => {
  if (isLoading.value || noMore.value) return;
  pageNo.value++; // 页码+1
  getCheckinTasks();
};

// 签到任务数据
const checkinTasks = ref<CheckinTaskItem[]>([
  // {
  //   id: 1,
  //   title: "社区志愿服务",
  //   status: "unapplied",
  //   desc: "参与社区组织的环保志愿服务活动，完成后可获得积分奖励",
  //   requirement: "需现场参与并完成2小时志愿服务",
  //   startTime: "2025-8-1",
  //   endTime: "2025-8-31",
  //   points: 100,
  //   tags: ["线下", "志愿", "环保"],
  //   participantCount: 125,
  //   locationRequired: true,
  //   checkinLocation: {
  //     name: "城市公园南门广场",
  //     latitude: 39.9087,
  //     longitude: 116.3975,
  //     radius: 100,
  //   },
  // },
  // {
  //   id: 2,
  //   title: "商场问卷调查",
  //   status: "unapplied",
  //   desc: "在指定商场完成消费者问卷调查，帮助商家改进服务质量",
  //   requirement: "完成20份有效问卷，需拍摄现场工作照片",
  //   startTime: "2025-8-5",
  //   endTime: "2025-8-15",
  //   points: 150,
  //   tags: ["线下", "调研", "商业"],
  //   participantCount: 84,
  //   locationRequired: true,
  //   checkinLocation: {
  //     name: "阳光购物中心一楼大厅",
  //     latitude: 39.9187,
  //     longitude: 116.4075,
  //     radius: 50,
  //   },
  // },
  // {
  //   id: 3,
  //   title: "图书馆整理",
  //   status: "unapplied",
  //   desc: "协助图书馆工作人员整理图书，维护阅读秩序",
  //   requirement: "需连续服务3小时，遵守图书馆管理规定",
  //   startTime: "2025-8-1",
  //   endTime: "2025-8-31",
  //   points: 80,
  //   tags: ["线下", "公益", "文化"],
  //   participantCount: 36,
  //   locationRequired: true,
  //   checkinLocation: {
  //     name: "市图书馆三楼阅览室",
  //     latitude: 39.9287,
  //     longitude: 116.4175,
  //     radius: 30,
  //   },
  // },
  // {
  //   id: 4,
  //   title: "校园宣传活动",
  //   status: "unapplied",
  //   desc: "在大学校园内宣传环保知识，发放宣传手册",
  //   requirement: "覆盖3个以上院系，发放不少于200份宣传材料",
  //   startTime: "2025-8-5",
  //   endTime: "2025-8-12",
  //   points: 120,
  //   tags: ["线下", "宣传", "教育"],
  //   participantCount: 29,
  //   locationRequired: true,
  //   checkinLocation: {
  //     name: "大学主校区广场",
  //     latitude: 39.9387,
  //     longitude: 116.4275,
  //     radius: 150,
  //   },
  // },
]);

// 根据状态获取显示文本
const getStatusText = (status: TaskStatus) => {
  const statusMap = {
    pending: "审核中",
    approved: "已通过",
    rejected: "已拒绝",
    unapplied: "未申请",
  };
  return statusMap[status] || "申请任务";
};

// 根据状态获取样式类
const getStatusClass = (status: TaskStatus) => {
  const classMap = {
    pending: "bg-[#fff3e0] text-[#f57c00]",
    approved: "bg-[#e8f5e9] text-[#43a047]",
    rejected: "bg-[#ffebee] text-[#e53935]",
    unapplied: "bg-[#e3f2fd] text-[#1976d2]",
  };
  return classMap[status] || "bg-[#e3f2fd] text-[#1976d2]";
};

// 切换筛选条件
const activeFilterType = (index: number, typeid: number) => {
  activeFilter.value = index;
  resetPagination(); // 重置分页
  getCheckinTasks();
};

// 处理任务申请
const handleApplyTask = (task: CheckinTaskItem) => {
  // 模拟申请提交
  Taro.showLoading({ title: "提交申请中..." });
  console.log("申请任务：", task);

  // 实际项目中这里会调用后台接口
  setTimeout(async () => {
    task.status = "pending";
    // API接口
    const res = await post("/check/register", {taskId: task.id});
    if (res.code == 0) {
      Taro.hideLoading();
      Taro.showToast({
        title: "申请已提交，请等待审核",
        icon: "none",
        duration: 2000,
      });
    }
  }, 1000);
};

// 处理重新申请
const handleReapply = (task: CheckinTaskItem) => {
  Taro.showModal({
    title: "重新申请",
    content: "是否确认重新申请该任务？请检查申请条件是否符合要求",
    success: (res) => {
      if (res.confirm) {
        task.status = "pending";
        Taro.showToast({
          title: "重新申请已提交",
          icon: "none",
          duration: 2000,
        });
      }
    },
  });
};

// 查看任务详情（只有审核通过的任务可以查看）
const handleViewDetail = (task: CheckinTaskItem) => {
  Taro.navigateTo({
    url: `/pages-detail/post/reward/checkin-task-detail?id=${task.id}`,
  });
};

// // 获取签到任务类型
// const getTaskType = async () => {
//   const res = await post("/dictionary/checkinType",{
//     id:2
//   });
//   console.log('签到任务类型==>',res);
//   if (res.code == 0) {
//     filters.value = res.data.map((item: any) => ({
//       id: item.columns.id,
//       name: item.columns.name,
//     }));
//   }
// };
// getTaskType();

// 获取签到任务数据
const getCheckinTasks = async () => {
  // 防止重复请求
  if (isLoading.value || noMore.value) {
    if (noMore.value) {
      Taro.showToast({ title: "没有更多了", icon: "none" });
    }
    return;
  }

  isLoading.value = true; // 开始加载

  try {
    const res = await post("/check/all", {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      title: searchValue.value,
    });
    
    if (res.code == 0) {
      console.log("签到任务数据==>", res);
      // 实际项目中根据接口返回数据处理
      const newItems = res.data.map((item: any) => item.columns);
      
      // 第一页直接赋值，后续页追加数据
      if (pageNo.value === 1) {
        checkinTasks.value = newItems;
      } else {
        checkinTasks.value = [...checkinTasks.value, ...newItems];
      }
      
      // 判断是否还有更多数据（当前页数据小于pageSize则说明没有更多）
      noMore.value = newItems.length < pageSize.value;
    }
  } catch (error) {
    console.error("获取签到任务数据失败：", error);
    Taro.showToast({ title: "加载失败", icon: "none" });
  } finally {
    isLoading.value = false; // 结束加载
  }
};
getCheckinTasks();
</script>
